package com.fll.fangyishare.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fll.fangyicommon.entity.ResultOk;
import com.fll.fangyicommon.entity.share.Comment;
import com.fll.fangyicommon.entity.share.Liked;
import com.fll.fangyicommon.entity.user.User;
import com.fll.fangyishare.service.CommentService;
import com.fll.fangyishare.service.LikedService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author fll
 * create 2023/3/25
 */
@RestController
@Slf4j
@RequestMapping("/share")
public class CommentController {

    @Autowired
    private CommentService commentService;

    //登录用户在某个share下发表评论
    @GetMapping("/addComment")
    public ResultOk addComment(@RequestParam Map<String, String> params, @RequestHeader String userInfo) {
        ResultOk<Comment> ok = new ResultOk<>();
        User user = null;
        Comment comment = new Comment();
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);

            comment.setUserId(user.getUserId());
            comment.setShareId(new Integer(params.get("shareId")));
            comment.setCommentContent(params.get("commentMsg"));
            comment.setCommentLike(0);
            Integer num = commentService.addComment(comment);
            if (num != -1){
                ok.setCode(200);
                ok.setMsg("评论成功");
                ok.setData(comment);
            } else {
                ok.setCode(400);
                ok.setMsg("评论失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("后端异常");
            return ok;
        }
        return ok;
    }

    //获取某条share的评论
    @GetMapping("/getComment")
    public ResultOk getShareComment(@RequestParam("shareId") Integer shareId, @RequestHeader String userInfo) {
        ResultOk<ArrayList<Comment>> ok = new ResultOk<>();
        User user = null;
        try {
            //为后期实现查看评论点赞用户
            user = new ObjectMapper().readValue(userInfo, User.class);
            ArrayList<Comment> allComment = commentService.getAllComment(shareId, user.getUserId());
            if (allComment != null){
                ok.setCode(200);
                ok.setMsg("获取成功");
                ok.setData(allComment);
                return ok;
            }
            ok.setCode(400);
            ok.setMsg("评论为空");
            ok.setData(null);
        } catch (IOException e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("后端异常");
            return ok;
        }
        return ok;
    }

}
